import React, { useEffect, useState } from "react";
import { Box, Typography, List, ListItem } from "@mui/material";
import Member from "./Member";
import { client } from "../../../api/appsync";

interface Member {
  id: string;
  name: string;
  avatar?: string;
}

const MemberList: React.FC<{ roomId: string }> = ({ roomId }) => {
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchMembers = async () => {
      try {
        /*const { data } = await client.graphql({
          query: `query GetRoomMembers($roomId: ID!) {
            getRoom(id: $roomId) {
              members {
                id
                name
                online
                avatar
              }
            }
          }`,
          variables: { roomId },
        });
        setMembers(data.getRoom.members);
        */

        const data: Member[] = [
          { id: "1", name: "name1", avatar: "string" },
          { id: "2", name: "same2", avatar: "string" },
        ];
        setMembers(data);
      } catch (error) {
        console.error("Error fetching members:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchMembers();

    /*
    const sub = client
      .graphql({
        query: `subscription OnMemberStatusChanged($roomId: ID!) {
        onMemberStatusChanged(roomId: $roomId) {
          id
          name
          online
          avatar
        }
      }`,
        variables: { roomId },
      })
      .subscribe({
        next: ({ data }) => {
          setMembers((prev) =>
            prev.map((member) =>
              member.id === data.onMemberStatusChanged.id
                ? data.onMemberStatusChanged
                : member
            )
          );
        },
        error: (error) => console.error("Subscription error:", error),
      });

    return () => sub.unsubscribe();
    */
  }, [roomId]);

  if (loading) return <Box p={2}>Loading members...</Box>;

  return (
    <Box
      sx={{
        width: 250,
        height: "100%",
        //borderLeft: "1px solid",
        //borderColor: "divider",
        bgcolor: "divider",
        overflowY: "auto",
      }}
    >
      <Box sx={{ textAlign: "left", padding: 1 }}>
        <Typography variant="h6" component="div">
          メンバー
        </Typography>
      </Box>
      <List>
        {members.map((member) => (
          <ListItem key={member.id}>
            <Member key={member.id} data={member} />
          </ListItem>
        ))}
      </List>
    </Box>
  );
};

export default MemberList;
